package com.ganzalang.gmall.designpatterns.visitor;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 使用访问者模式
 * @auhtor: ganzalang
 */
@Slf4j
public class VisitorPatternDemo {

    public static void main(String[] args) {
        Department leafDept1 = new Department("叶子节点1");
        Department leafDept2 = new Department("叶子节点2");
        Department leafDept3 = new Department("叶子节点3");

        Department subDept1 = new Department("子节点1");
        subDept1.getChildren().add(leafDept1);
        subDept1.getChildren().add(leafDept2);

        Department subDept2 = new Department("子节点2");
        subDept2.getChildren().add(leafDept3);

        Department parentDept = new Department("父节点");
        parentDept.getChildren().add(subDept1);
        parentDept.getChildren().add(subDept2);

        DeleteVisitor deleteVisitor = new DeleteVisitor();
        parentDept.accept(deleteVisitor);

        UpdateStatusVisitor updateStatusVisitor = new UpdateStatusVisitor("禁用");
        parentDept.accept(updateStatusVisitor);
    }

    public static class Department {
        private String name;
        private List<Department> children = new ArrayList<>();

        public Department(String name) {
            this.name = name;
        }

        public void setChildren(List<Department> children) {
            this.children = children;
        }

        public List<Department> getChildren() {
            return children;
        }

        public void accept(Visitor visitor) {
            visitor.visitor(this);
        }

    }

    public interface Visitor {
        void visitor(Department dept);
    }

    public static class DeleteVisitor implements Visitor{

        @Override
        public void visitor(Department dept) {
            if (dept.getChildren().size() > 0) {
                for (Department child : dept.getChildren()) {
                    child.accept(this);
                }
            }
            log.info("删除节点" + dept.name);
        }
    }

    public static class UpdateStatusVisitor implements Visitor{
        private String status;

        public UpdateStatusVisitor(String status) {
            this.status = status;
        }

        @Override
        public void visitor(Department dept) {
            if (dept.getChildren().size() > 0) {
                for (Department child : dept.getChildren()) {
                    child.accept(this);
                }
            }
            log.info("更新节点" + dept.name + "状态为" + status);
        }
    }

}
